/*
 * @Author: william-occam
 * @Date: 2024-07-22 17:10:33
 * @LastEditors: william-occam
 * @LastEditTime: 2024-10-15 22:24:11
 * @FilePath: \draw-project\src\views\welcome\columns.tsx
 * @Description:
 *
 *  Copyright 2024 by GETECH  Co., Ltd. All Rights Reserved.
 *  Licensed under the GETECH License,  Version 1.0;
 *  https://www.getech.cn/licenses/LICENSE-1.0
 */
import { useZhuanJiaListStore } from "@/store/modules/zhuanjiaList";
import { AdaptiveConfig } from "@pureadmin/table";
import { onMounted, reactive, ref } from "vue";
// import { options } from "../data";
import * as XLSX from 'xlsx';
export function useColumns() {
  const dataList = ref([]);
  const zhuanJiaListStore = useZhuanJiaListStore()

  const columns: TableColumnList = [
    {
      label: "序号",
      prop: "seqNo",
    },
    {
      label: "专家姓名",
      prop: "name",
      cellRenderer: ({ row }) => <el-input v-model={row.name} />
    },
    {
      label: "专家证号",
      prop: "cardID",
      cellRenderer: ({ row }) => <el-input v-model={row.cardID} />
    },
    {
      label: "联系电话",
      prop: "telNum",
      cellRenderer: ({ row }) => <el-input v-model={row.telNum} />,
      minWidth: 110
    },
    {
      label: "操作",
      fixed: "right",
      width: 90,
      slot: "operation"
    }
  ];

  function onAdd() {


    dataList.value.push({
      seqNo: dataList.value.length + 1,
      name: "",
      cardID: "",
      telNum: "",
    });
  }

  function onDel(row) {
    const index = dataList.value.indexOf(row);
    if (index !== -1) dataList.value.splice(index, 1);
    dataList.value.forEach((v, i) => {
      v.seqNo = i+1
    })
    zhuanJiaListStore.setZhuanJiaList(dataList.value || [])
  }

  /** 撑满内容区自适应高度相关配置 */
  const adaptiveConfig: AdaptiveConfig = {
    /** 表格距离页面底部的偏移量，默认值为 `96` */
    offsetBottom: 110
    /** 是否固定表头，默认值为 `true`（如果不想固定表头，fixHeader设置为false并且表格要设置table-layout="auto"） */
    // fixHeader: true
    /** 页面 `resize` 时的防抖时间，默认值为 `60` ms */
    // timeout: 60
    /** 表头的 `z-index`，默认值为 `100` */
    // zIndex: 100
  };

  const selectOptions = reactive([
    { value: 'gongcheng', label: '工程类' },
    { value: 'zhengfucaigou', label: '政府采购类' },
    { value: 'yiliao', label: '医疗类' }
  ]);
  const selectVal = ref('gongcheng');
  const fileList = [];

  /**
   * @description: 导入时间
   * @param {*} event
   * @param {*} fileList
   * @return {*}
   */
  const handleChange = async  (ev) => {


    let file = ev.raw;
    if (selectVal.value === 'gongcheng') {
      localStorage.setItem('gongChengFilePath', file?.path);
    } else if (selectVal.value === 'yiliao') {
      localStorage.setItem('yiliaoFilePath', file?.path);
    }else {
      localStorage.setItem('zhengFuFilePath', file?.path);
    }

      if(!file){
        return ;
      }else{
       let data = await readFile(file);
       let workbook = XLSX.read(data,{ type: "binary"});//解析二进制格式数据
       console.log(workbook)
       let worksheet = workbook.Sheets[workbook.SheetNames[0]];//获取第一个Sheet
       let result = XLSX.utils.sheet_to_json(worksheet);//json数据格式
        dataList.value = resolvingData(result);
        if (selectVal.value === 'gongcheng') {
          zhuanJiaListStore.setZhuanJiaList(dataList.value || [])
        } else if (selectVal.value === 'yiliao') {
          zhuanJiaListStore.setYiliaoList(dataList.value || [])
        }
        else {
          zhuanJiaListStore.setZhengFulistList(dataList.value || [])
        }
      }
  }

  /**
   * @description:
   * @param {*} e
   * @return {*}
   */
  const selectChange = (e) => {
    if (e === 'gongcheng') {
      dataList.value = zhuanJiaListStore.zhuanJiaList
    } else if (e === 'yiliao') {
      dataList.value = zhuanJiaListStore.yiliaoList
    }
    else {
      dataList.value = zhuanJiaListStore.zhengFulist
    }
  }

  const readFile = (file) =>{//文件读取
    return new Promise(resolve => {
      let reader = new FileReader();
      reader.readAsBinaryString(file);//以二进制的方式读取
      reader.onload = ev =>{
        resolve(ev.target.result);
      }
    })
  }

  onMounted(() => {
    dataList.value = zhuanJiaListStore.zhuanJiaList
  })

  const exportExcel = () => {
    const res = dataList.value.map(item => {
      const arr = [];
      columns.forEach(column => {
        arr.push(item[column.prop as string]);
      });
      return arr;
    });
    const titleList = [];
    columns.forEach(column => {
      titleList.push(column.label);
    });
    res.unshift(titleList);
    const workSheet = XLSX.utils.aoa_to_sheet(res);
    const workBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workBook, workSheet, "数据报表");
    let tableName = '';
    if (selectVal.value === 'gongcheng') {
      tableName = '工程类'
    }
    else if (selectVal.value === 'yiliao') {
      tableName = '医疗类'
    }
    else {
      tableName = '政府采购类'
    }

    XLSX.writeFile(workBook, `${tableName}抽取表.xlsx`);

  };

  const resolvingData = (dataList: any[]) => {
    return dataList?.filter(val => typeof val['XXXXX -专家抽取表'] === 'number').map((v: any) => {
      const seqNo = v['XXXXX -专家抽取表'];
      const name = v['__EMPTY'];
      const cardID = v['__EMPTY_1'];
      const telNum = v['__EMPTY_2'];
      return {
        seqNo,
        name,
        cardID,
        telNum
      }
    });
  }

  return {
    columns,
    dataList,
    onAdd,
    onDel,
    selectOptions,
    adaptiveConfig,
    selectVal,
    fileList,
    handleChange,
    selectChange,
    zhuanJiaListStore,
    exportExcel,
    resolvingData
  };
}
